package com.association.controller;

import com.association.logging.aop.log.WebLog;
import com.association.model.entity.User;
import com.len.JsonResult;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author 18244
 */
@RestController
public class UploadController {

    private static String filePath = "D:/association/association-project/server/association-server/mass-admin/src/main/resources/static/pageImg";

    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @explain 上传图片
     * @author  BianPeng
     * @time    2019年4月9日
     */
    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        //1.后半段目录：  2020/03/15
        String directory = sdf.format(date);
        /**
         *  2.文件保存目录  E:/images/2020/03/15/
         *  如果目录不存在，则创建
         */
        File dir = new File(filePath+ "/" + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //3.给文件重新设置一个名字
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;
        //4.创建这个新文件
        File newFile = new File(filePath+ "/" + directory+ "/" + newFileName);
        //5.复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = directory+ "/" + newFileName;
            logger.info("上传成功:"+url);
            return url;
        } catch (IOException e) {
            logger.error("上传失败:"+e.getMessage());
            return null;
        }
    }
}
